package com.dld.coupon.view;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.constant.net.Constant;
import com.dld.android.net.Param;
import com.dld.android.persistent.SharePersistent;
import com.dld.coupon.activity.ActivityManager;
import com.dld.coupon.activity.BaseActivity;
import com.dld.coupon.activity.DetailActivity;
import com.dld.coupon.activity.MyCouponDetail;
import com.dld.coupon.activity.R;
import com.dld.coupon.activity.StoreDetail;
import com.dld.coupon.util.MapUtil;
import com.dld.coupon.util.StringUtils;
import com.dld.protocol.ProtocolHelper;
import com.dld.protocol.json.Coupon;
import com.dld.protocol.json.CouponDetail;
import com.dld.protocol.json.PageInfo;
import com.dld.protocol.json.Protocol;
import com.tencent.weibo.utils.Cache;

public class RecommendLinearLayout extends ListTab implements MainViewBase {
	protected DownloadListView.DownLoadAdapter adapter;
	private Coupon coupon = new Coupon();
	Handler handler = new Handler();
	protected boolean isFirst = true;
	private String lastUrl = "";
	private double lat = 0.0D;
	protected DownloadListView list;
	private double lng = 0.0D;
	protected int pageIndex = 1;
	private ProtocolCreator protocolCreator;
	private boolean search;
	private String keyword;
	private int searchType;
	private int cate_code;

	public RecommendLinearLayout(Context paramContext,
			AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
	}

	private void initRefresh() {
		findViewById(R.id.refresh).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View paramView) {
						RecommendLinearLayout.this.request(true, MapUtil
								.getCityId());
					}
				});
	}

	protected DownloadListView.DownLoadAdapter getAdapter(
			DownloadListView paramDownloadListView, boolean paramBoolean) {
		return new ListViewAdapter(paramDownloadListView, this.coupon,
				Constant.VIEW_COUPON);
	}

	protected AdapterView.OnItemClickListener getItemClickListener() {
		return new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> paramAdapterView,
					View paramView, int paramInt, long paramLong) {
				CouponDetail cdd = (CouponDetail) paramView.getTag();

				Cache.put("coupon", RecommendLinearLayout.this.coupon);
				Cache.put("protocol",
						RecommendLinearLayout.this.protocolCreator
								.createProtocol(
										RecommendLinearLayout.this.activity,
										new Param()));
				Intent it = new Intent(paramView.getContext(),
						MyCouponDetail.class);
				it.putExtra(Constant.CONSTANT_DISID, "" + cdd.getDisid());
				it.putExtra("previous_pos", BaseActivity.segmentPosition);
				Log.v("", ":discount id " + cdd.getDisid());
				paramView.getContext().startActivity(it);
			}
		};
	}

	protected void init() {
		try {
			Log.v("", "************  init category id  " + this.category.id);
			if (!this.isFirst)
				init(this.protocolCreator, null, false, this.category.code,
						this.search);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void init(ProtocolCreator paramProtocolCreator,
			String paramString, boolean paramBoolean1, int paramInt,
			boolean paramBoolean2) {
		this.search = paramBoolean2;
		if (paramProtocolCreator != null)
			this.protocolCreator = paramProtocolCreator;
		else {
			this.protocolCreator = new ProtocolCreator() {
				public Protocol createProtocol(Context cnt, Param param) {
					param.append("r", "www/api/list").append("userAgent",
							"dld_android").append("module", "discount");
					return ProtocolHelper.recommondCoupon(cnt, param);
				}
			};

		}
		this.list = ((DownloadListView) findViewById(R.id.listview));
		this.list.setOnItemClickListener(getItemClickListener());
		this.adapter = getAdapter(this.list, paramBoolean2);
		this.list.setAdapter(this.adapter);
		initAddressList(paramString, paramBoolean1);
		initCategoryList(paramInt);
		initRefresh();
		request();
	}

	public void onHide() {
		this.showing = false;
		hideList();
	}

	public void onShow() {
		show(null, null, false, 100, false, null, 1);
	}

	protected void request() {
		request(false, MapUtil.getCityId());
	}

	protected void request(boolean paramBoolean, String cityid) {

		try {
			Param param = new Param();
			Log
					.v("", "request *****************　"
							+ System.currentTimeMillis());

			if (keyword != null) {
				param.append("r", "www/api/search");
				param.append("userAgent", "dld_android");
				param.append("keyword", keyword);
				param.append("areaCode", cityid);
				param.append("searchType", "" + this.searchType);
			} else {
				param.append("r", "www/api/list");
				param.append("userAgent", "dld_android");
				param.append("module", "around");
				param.append("areaCode", cityid);
				if (this.category.code != 100) {
					param.append("categoryCode", "" + this.category.code);
				}
				param.append("viewType", "2");
			}
			if (!StringUtils.isEmpty(cityid)) {
				if (paramBoolean) {
					for (int i = 1; i <= this.pageIndex; i++)
						Cache.remove(this.protocolCreator.createProtocol(
								this.activity, param).getAbsoluteUrl());
					this.pageIndex = 1;
				}
				if (this.pageIndex == 1) {
					this.coupon.details.clear();
					this.list.reset();
				}
				param.append("pageSize", "10");
				param.append("currentPage", "" + this.pageIndex);
				Protocol localProtocol = this.protocolCreator.createProtocol(
						ActivityManager.getCurrent(), param);
				this.lastUrl = localProtocol.getAbsoluteUrl();
				localProtocol.startTrans(new RecommendProtocolResult(
						String.class));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void show(ProtocolCreator paramProtocolCreator, String paramString,
			boolean paramBoolean1, int paramInt, boolean paramBoolean2,
			String keyword, int searchType) {
		this.showing = true;
		this.keyword = keyword;
		this.searchType = searchType;
		String str = SharePersistent.getInstance().getPerference(this.activity,
				"city_id");
		if (!this.isFirst) {
			if ((StringUtils.isEmpty(this.cityId)) || (this.cityId.equals(str))) {
				if (StringUtils.isEmpty(str)) {
					SharePersistent.getInstance().getPerference(this.activity,
							"city_id");
					this.pageIndex = 0;
					request();
				}
			} else
				init(paramProtocolCreator, paramString, paramBoolean1,
						paramInt, paramBoolean2);
		} else {
			init(paramProtocolCreator, paramString, paramBoolean1, paramInt,
					paramBoolean2);
			this.isFirst = false;
		}
	}

	private class ListViewAdapter extends CouponDownLoadAdapter {
		public ListViewAdapter(DownloadListView paramCoupon,
				Coupon paramBoolean, int view_type) {
			super(false, paramCoupon, paramBoolean, view_type);
		}

		public Context getContext() {
			return RecommendLinearLayout.this.activity;
		}

		public View getView(int paramInt) {
			View localView = super.getView(paramInt);
			localView.findViewById(R.id.coupon_distance_text).setVisibility(
					View.GONE);
			return localView;
		}

		public void onNotifyDownload() {
			RecommendLinearLayout.this.pageIndex = getListCount() / 10 + 1;
			RecommendLinearLayout.this.request();
		}
	}

	public static abstract interface ProtocolCreator {
		public abstract Protocol createProtocol(Context cnt, Param param);
	}

	protected class RecommendProtocolResult extends
			Protocol.OnJsonProtocolResult {
		public RecommendProtocolResult(Class cls) {
			super(cls);
		}

		private void notifyNoResult() {
			RecommendLinearLayout.this.handler.post(new Runnable() {
				public void run() {
					RecommendLinearLayout.this.adapter.notifyNoResult();
				}
			});
		}

		public void onException(String paramString, Exception paramException) {
			if (RecommendLinearLayout.this.lastUrl.equals(paramString))
				notifyNoResult();
		}

		public void onResult(String paramString, final Object paramObject) {
			RecommendLinearLayout.this.activity.runOnUiThread(new Runnable() {
				public void run() {
					try {
						String content = (String) paramObject;
						Element root = DocumentBuilderFactory.newInstance()
								.newDocumentBuilder().parse(
										new ByteArrayInputStream(content
												.getBytes()))
								.getDocumentElement();

						try {
							NodeList lsittotal = root
									.getElementsByTagName("total");
							String total = lsittotal.item(0).getFirstChild()
									.getNodeValue();
							PageInfo pinfo = new PageInfo();
							pinfo.total = Integer.parseInt(total);
							if (pinfo.total != 0) {
								List<CouponDetail> nlist = CouponDetail
										.fromXmlToAdroundInfo(root);
								RecommendLinearLayout.this.coupon.details
										.addAll(nlist);
								RecommendLinearLayout.this.coupon.pageInfo = pinfo;
								RecommendLinearLayout.this.adapter
										.notifyDownloadBack();
							} else {
								notifyNoResult();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	@Override
	protected void requestBy(String cityid) {
		request(false, cityid);
	}
}
